/*
 * @Author: yangzonglong
 * @Date: 2021-05-12 16:11:38
 * @version: v1.0.0
 * @Descripttion: 编辑工作流
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-07-28 16:35:40
 * @Auditor: 
 */
import React, { useEffect, useState, useMemo } from 'react';
import DetailsLayout from './../detailsLayout/DetailsLayout';
import Toolbar from './toolbar/_Toolbar';
import StartEvent from './startEvent/_StartEvent';
import SequenceFlow from './sequenceFlow/_SequenceFlow';
import UserTask from './userTask/_UserTask';
import EndEvent from './endEvent/EndEvent';
import ReceiveTask from './receiveTask/ReceiveTask';
import ScriptTask from './scriptTask/_ScriptTask';
import { StartEventSelfProps, UserTaskSelfProps, SequenceFlowSelfProps } from './../../interface';
import Context from './context';
import style from './style.module.scss';

import Modeler from 'bpmn-js/lib/Modeler';
import camundaJSON from './configs/camunda.json';
import huilianJSON from './configs/huilian.json';
import INIT_XML from './configs/initXML';
import 'bpmn-js/dist/assets/bpmn-js.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
import 'bpmn-js/dist/assets/diagram-js.css';

const WfEditor =  ({ workflowId, bpmnContent }) => {
  const [modeler, setModeler] = useState<any>({});
  const [self, setSelf] = useState<StartEventSelfProps | UserTaskSelfProps | SequenceFlowSelfProps>({})


  useEffect(() => {
    // if (!workflow.bpmnContent) return;

    const modeler = new Modeler({
      container: '#modeler',
      // propertiesPanel: { parent: '#propertiesPanelParent' },
      keyboard: { bindTo: document.body },
      moddleExtensions: { huilian: huilianJSON, camunda: camundaJSON }
    })

    modeler.importXML(bpmnContent || INIT_XML).then((result) => {
      modeler.on('element.changed', (ev: any) => {
      })

      modeler.on('selection.changed', (ev: any) => {
        setSelf(ev.newSelection?.[0]);
      })

      setModeler(modeler);
    }).catch(err => {
      console.error(err)
    })

    return () => modeler.destroy();
  }, [bpmnContent]);

  const Aside = useMemo(() => {
    if (self?.type === 'bpmn:StartEvent') return <StartEvent key={(self as any).id}/>;
    if (self?.type === 'bpmn:SequenceFlow') return <SequenceFlow key={(self as any).id}/>;
    if (self?.type === 'bpmn:UserTask') return <UserTask key={(self as any).id}/>;
    if (self?.type === 'bpmn:EndEvent') return <EndEvent key={(self as any).id}/>;
    if (self?.type === 'bpmn:ReceiveTask') return <ReceiveTask key={(self as any).id}/>;
    if(self?.type === 'bpmn:ScriptTask') return <ScriptTask key={(self as any).id}/>;
    return null
  }, [self]);

  return (
    <Context.Provider value={{ self, modeler }}>
      <DetailsLayout aside={Aside && Aside}>
        <div id='modeler' className={style.bpmnContent} />
        <Toolbar modeler={modeler} workflowId={workflowId} />
      </DetailsLayout>
    </Context.Provider>
  )
}

export default WfEditor